<template>
  <div class="emotion-analysis-page">
    <!-- 顶部导航栏 -->
    <header class="emotion-header">
      <button class="back-button" @click="goToHome" title="返回首页">
        ← 返回
      </button>
      <h1 class="page-title">我的情绪分析</h1>
      <button class="export-button" @click="exportReport" title="导出报告">
        导出报告
      </button>
    </header>

    <!-- 筛选区 -->
    <div class="filter-section">
      <div class="filter-buttons">
        <button 
          v-for="period in periods" 
          :key="period.value"
          :class="['filter-btn', { active: selectedPeriod === period.value }]"
          @click="selectPeriod(period.value)"
        >
          {{ period.label }}
        </button>
      </div>
    </div>

    <!-- 核心数据区 -->
    <main class="core-data-section">
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载情绪分析数据...</p>
      </div>
      
      <!-- 错误提示 -->
      <div v-else-if="error" class="error-container">
        <p class="error-message">{{ error }}</p>
      </div>
      
      <!-- 有数据时显示分析内容 -->
      <template v-else-if="hasEmotionData">
        <!-- 情绪趋势图 -->
        <div class="trend-chart-container">
          <div class="chart-wrapper">
            <div class="chart-content" ref="chartContainer" @mousemove="handleChartMouseMove" @mouseleave="handleChartMouseLeave">
              <!-- 图表网格 -->
              <div class="chart-grid">
                <div v-for="y in 10" :key="`grid-${y}`" class="grid-line" :style="{ bottom: `${(y - 1) * 10}%` }"></div>
              </div>
              
              <!-- Y轴标签 -->
              <div class="y-axis">
                <span v-for="y in 10" :key="`y-${y}`" class="y-label" :style="{ bottom: `${(y - 1) * 10}%` }">{{ y }}</span>
              </div>
              
              <!-- X轴标签 -->
              <div class="x-axis">
                <span v-for="(date, index) in chartDates" :key="`x-${index}`" class="x-label" :style="{ left: `${index * (100 / (chartDates.length - 1))}%` }">{{ formatDate(date) }}</span>
              </div>
              
              <!-- 折线图 -->
              <div class="line-chart">
                <!-- 线条 -->
                  <svg class="chart-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
                    <!-- 主线条 - 更细的黑色 -->
                    <path :d="getLinePath()" fill="none" stroke="#000" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round" />
                    
                    <!-- 数据点 - 更细节的黑色小节点 -->
                    <circle 
                      v-for="(point, index) in chartData" 
                      :key="`point-${index}`"
                      :cx="`${index * (100 / (chartData.length - 1))}`"
                      :cy="`${100 - point * 10}`"
                      :r="1"
                      fill="#000"
                      stroke="#000"
                      stroke-width="0.3"
                      :class="{ 'active': highlightedPoint === index }"
                      @mouseover="highlightPoint(index)"
                      transition="all 0.3s ease"
                    />
                  </svg>
              </div>
              
              <!-- 数据点气泡 -->
              <div 
                v-if="tooltipVisible" 
                class="data-tooltip" 
                :style="{ left: tooltipLeft + 'px', top: tooltipTop + 'px' }"
              >
                {{ tooltipContent }}
              </div>
            </div>
          </div>
        </div>

        <!-- 情绪总结卡片 -->
        <div class="summary-cards">
          <!-- 主要情绪卡片 -->
          <div class="summary-card">
            <h3 class="card-title" style="color: var(--accent-color)">{{ periodLabel }}主要情绪</h3>
            <div class="emotion-tag" :style="{ color: getEmotionColor(mainEmotion) }">{{ mainEmotion }}</div>
            <p class="emotion-percentage">占比{{ emotionPercentage }}%</p>
          </div>
          
          <!-- 高频关键词卡片 -->
          <div class="summary-card">
            <h3 class="card-title" style="color: var(--secondary-color)">高频关键词</h3>
            <div class="keywords">
              <span v-for="(keyword, index) in keywords" :key="index" class="keyword-tag">{{ keyword }}</span>
            </div>
          </div>
          
          <!-- 情绪健康度卡片 -->
          <div class="summary-card">
            <h3 class="card-title" style="color: var(--accent-light)">情绪健康度</h3>
            <div class="health-progress-container">
              <div class="health-progress-bar">
                <div class="health-progress-fill" :style="{ width: `${healthScore}%` }"></div>
              </div>
              <span class="health-score">{{ healthScore }}%</span>
            </div>
          </div>
        </div>

        <!-- 疏导建议区 -->
        <div class="suggestions-section">
          <div class="suggestions-card">
            <h3 class="suggestions-title">专属情绪建议</h3>
            <div class="suggestions-list">
              <div v-for="(suggestion, index) in suggestions" :key="index" class="suggestion-item">
                <span class="suggestion-dot"></span>
                <span class="suggestion-text">{{ suggestion }}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
      
      <!-- 没有数据时显示暂无数据 -->
      <template v-else>
        <div class="no-data-container">
          <div class="no-data-content">
            <div class="no-data-icon">📝</div>
            <h3 class="no-data-title">暂无情绪数据</h3>
            <p class="no-data-description">写日记是记录和了解自己情绪的好方法</p>
            <button class="start-writing-btn" @click="goToDiary">开始写日记</button>
          </div>
        </div>
      </template>
    </main>

    <!-- 有数据时显示推荐 -->
    <section v-if="hasEmotionData" class="recommendations-section">
      <h3 class="recommendations-title">为你推荐</h3>
      <div class="recommendations-list">
        <div 
          v-for="(article, index) in recommendedArticles" 
          :key="index"
          class="article-card"
          @click="openArticle(index)"
        >
          <h4 class="article-title">{{ article.title }}</h4>
          <div class="article-meta">
            <span class="article-time">{{ article.readTime }}</span>
            <span :class="['article-tag', `tag-${article.tagColor}`]">{{ article.tag }}</span>
          </div>
        </div>
      </div>
    </section>

    <!-- 导出提示 -->
    <div v-if="showExportMessage" class="export-message" :class="{ success: exportSuccess }">
      {{ exportMessage }}
    </div>
  </div>
</template>

<script>
import memberService from '../services/memberService'
import diaryService from '../services/diaryService'

export default {
  name: 'EmotionAnalysisView',
  data() {
    return {
      selectedPeriod: 'month', // 默认选中月度
      periods: [
        { label: '月度', value: 'month' },
        { label: '季度', value: 'quarter' },
        { label: '年度', value: 'year' }
      ],
      chartData: [], // 图表数据
      chartDates: [], // 图表日期
      mainEmotion: '', // 主要情绪
      emotionPercentage: 0, // 情绪占比
      keywords: [], // 高频关键词
      healthScore: 0, // 情绪健康度
      suggestions: [], // 疏导建议
      recommendedArticles: [], // 推荐文章
      highlightedPoint: -1, // 高亮的数据点索引
      tooltipVisible: false, // 是否显示工具提示
      tooltipLeft: 0, // 工具提示的X坐标
      tooltipTop: 0, // 工具提示的Y坐标
      tooltipContent: '', // 工具提示的内容
      showExportMessage: false, // 是否显示导出消息
      exportSuccess: false, // 导出是否成功
      exportMessage: '', // 导出消息内容
      isLoading: true, // 初始化为加载状态
      error: null // 错误信息
    }
  },
  
  computed: {
    // 检查是否有情绪日记数据
    hasEmotionData() {
      // 实际项目中应该检查真实的数据来源
      // 这里为了演示，我们假设当chartData有数据时表示有情绪日记
      return this.chartData.length > 0;
    },
    // 周期标签
    periodLabel() {
      const period = this.periods.find(p => p.value === this.selectedPeriod)
      return period ? period.label : ''
    }
  },
  async mounted() {
    // 初始化数据
    await this.updateData()
  },
  async activated() {
    // 当组件被重新激活时（比如从其他页面返回），重新更新数据
    console.log('EmotionAnalysisView activated, updating data')
    await this.updateData()
  },
  methods: {
    // 返回首页
    goToHome() {
      this.$router.push('/')
    },
    
    // 跳转到日记页面
    goToDiary() {
      // 假设日记创建页面的路由是'/diary/create'
      this.$router.push('/diary/create')
    },
    
    // 选择周期
    selectPeriod(period) {
      this.selectedPeriod = period
      this.updateData()
    },
    
    // 更新数据
    async updateData() {
      this.isLoading = true;
      this.error = null;
      
      try {
        // 调用后端API获取日记数据
        const entries = await diaryService.getDiaryList();
        console.log('从后端获取的日记数据:', entries);
        
        // 确保entries是数组格式
        const diaryEntries = Array.isArray(entries) ? entries : (entries.records || []);
      
        // 根据所选周期生成对应的数据
        this.generateChartData(diaryEntries);
        
        // 计算主要情绪和其他统计数据
        this.calculateMainEmotions(diaryEntries);
        this.calculateHealthScore(diaryEntries);
        this.generateSuggestionsAndKeywords(diaryEntries);
      } catch (error) {
        console.error('获取日记数据失败:', error);
        // 出错时清空数据，但不显示错误信息，而是保持无数据状态
        this.error = null; // 不显示错误提示
        this.chartData = [];
        this.chartDates = [];
        this.mainEmotion = '';
        this.emotionPercentage = 0;
        this.keywords = [];
        this.healthScore = 0;
        this.suggestions = [];
        this.recommendedArticles = [];
      } finally {
        this.isLoading = false;
      }
    },
    
    // 根据所选周期生成图表数据
    generateChartData(entries) {
      // 清空当前图表数据
      this.chartData = [];
      this.chartDates = [];
      
      // 根据所选周期处理数据
      switch (this.selectedPeriod) {
        case 'month':
          this.processMonthlyData(entries);
          break;
        case 'quarter':
          this.processQuarterlyData(entries);
          break;
        case 'year':
          this.processYearlyData(entries);
          break;
      }
    },
    
    // 处理月度数据
    processMonthlyData(entries) {
      const today = new Date();
      const currentMonth = today.getMonth();
      const currentYear = today.getFullYear();
      
      // 筛选当前月的数据
      const monthlyEntries = entries.filter(entry => {
        if (!entry.date) return false;
        const entryDate = new Date(entry.date);
        return entryDate.getMonth() === currentMonth && entryDate.getFullYear() === currentYear;
      });
      
      // 按日期分组
      const entriesByDate = {};
      monthlyEntries.forEach(entry => {
        if (!entry.date) return;
        const dateKey = new Date(entry.date).toDateString();
        if (!entriesByDate[dateKey]) {
          entriesByDate[dateKey] = [];
        }
        entriesByDate[dateKey].push(entry);
      });
      
      // 生成当月的日期序列（最近30天）
      for (let i = 29; i >= 0; i--) {
        const date = new Date();
        date.setDate(today.getDate() - i);
        const dateKey = date.toDateString();
        const dayEntries = entriesByDate[dateKey] || [];
        
        if (dayEntries.length > 0) {
          // 计算当天的平均心情分数
          const totalScore = dayEntries.reduce((sum, entry) => 
            sum + (entry.moodScore ? parseFloat(entry.moodScore) : 0), 0);
          const avgScore = totalScore / dayEntries.length;
          
          this.chartData.push(avgScore);
          this.chartDates.push(date);
        } else {
          // 没有数据的日期填充0
          this.chartData.push(0);
          this.chartDates.push(date);
        }
      }
    },
    
    // 处理季度数据
    processQuarterlyData(entries) {
      const today = new Date();
      const currentDate = today.getTime();
      const threeMonthsAgo = currentDate - (90 * 24 * 60 * 60 * 1000);
      
      // 筛选最近三个月的数据
      const quarterlyEntries = entries.filter(entry => {
        if (!entry.date) return false;
        return new Date(entry.date).getTime() >= threeMonthsAgo;
      });
      
      // 按周分组
      const entriesByWeek = {};
      quarterlyEntries.forEach(entry => {
        if (!entry.date) return;
        const entryDate = new Date(entry.date);
        const weekStart = this.getWeekStartDate(entryDate);
        const weekKey = weekStart.toDateString();
        
        if (!entriesByWeek[weekKey]) {
          entriesByWeek[weekKey] = [];
        }
        entriesByWeek[weekKey].push(entry);
      });
      
      // 生成最近12周的数据
      for (let week = 11; week >= 0; week--) {
        const weekStart = new Date();
        weekStart.setDate(today.getDate() - week * 7);
        const weekKey = this.getWeekStartDate(weekStart).toDateString();
        const weekEntries = entriesByWeek[weekKey] || [];
        
        if (weekEntries.length > 0) {
          const totalScore = weekEntries.reduce((sum, entry) => 
            sum + (entry.moodScore ? parseFloat(entry.moodScore) : 0), 0);
          const avgScore = totalScore / weekEntries.length;
          
          this.chartData.push(avgScore);
          this.chartDates.push(weekStart);
        } else {
          this.chartData.push(0);
          this.chartDates.push(weekStart);
        }
      }
    },
    
    // 处理年度数据
    processYearlyData(entries) {
      const currentYear = new Date().getFullYear();
      
      // 筛选当年的数据
      const yearlyEntries = entries.filter(entry => {
        if (!entry.date) return false;
        return new Date(entry.date).getFullYear() === currentYear;
      });
      
      // 按月份分组
      const entriesByMonth = {};
      for (let i = 0; i < 12; i++) {
        entriesByMonth[i] = [];
      }
      
      yearlyEntries.forEach(entry => {
        if (!entry.date) return;
        const monthKey = new Date(entry.date).getMonth();
        entriesByMonth[monthKey].push(entry);
      });
      
      // 生成12个月的数据
      for (let month = 0; month < 12; month++) {
        const monthEntries = entriesByMonth[month];
        const monthDate = new Date(currentYear, month, 1);
        
        if (monthEntries.length > 0) {
          const totalScore = monthEntries.reduce((sum, entry) => 
            sum + (entry.moodScore ? parseFloat(entry.moodScore) : 0), 0);
          const avgScore = totalScore / monthEntries.length;
          
          this.chartData.push(avgScore);
          this.chartDates.push(monthDate);
        } else {
          this.chartData.push(0);
          this.chartDates.push(monthDate);
        }
      }
    },
    
    // 获取指定日期所在周的开始日期（周一）
    getWeekStartDate(date) {
      const d = new Date(date);
      const day = d.getDay() || 7; // 将0（周日）转换为7
      d.setDate(d.getDate() - day + 1);
      d.setHours(0, 0, 0, 0);
      return d;
    },
    
    // 计算主要情绪
    calculateMainEmotions(entries) {
      const emotionCounts = {};
      
      entries.forEach(entry => {
        if (entry.emotion) {
          emotionCounts[entry.emotion] = (emotionCounts[entry.emotion] || 0) + 1;
        }
      });
      
      // 找出最常见的情绪
      let mainEmotion = '';
      let maxCount = 0;
      for (const [emotion, count] of Object.entries(emotionCounts)) {
        if (count > maxCount) {
          maxCount = count;
          mainEmotion = emotion;
        }
      }
      
      // 转换为中文标签
      const emotionLabels = {
        'happy': '开心',
        'sad': '悲伤',
        'angry': '愤怒',
        'anxious': '焦虑',
        'calm': '平静',
        'confused': '迷茫'
      };
      
      this.mainEmotion = emotionLabels[mainEmotion] || '平静';
      this.emotionPercentage = entries.length > 0 ? Math.round((maxCount / entries.length) * 100) : 0;
    },
    
    // 计算健康分数
    calculateHealthScore(entries) {
      if (entries.length === 0) {
        this.healthScore = 0;
        return;
      }
      
      // 计算平均心情分数
      const totalScore = entries.reduce((sum, entry) => 
        sum + (entry.moodScore ? parseFloat(entry.moodScore) : 0), 0);
      const avgMoodScore = totalScore / entries.length;
      
      // 根据平均心情分数计算健康分数（将1-10的心情分转换为0-100的健康分）
      this.healthScore = Math.round((avgMoodScore / 10) * 100);
    },
    
    // 生成建议和关键词
    generateSuggestionsAndKeywords(entries) {
      // 根据情绪分析生成关键词
      const commonKeywords = {
        'happy': ['积极', '快乐', '成就', '满足'],
        'sad': ['支持', '理解', '陪伴', '希望'],
        'angry': ['冷静', '理解', '沟通', '释放'],
        'anxious': ['放松', '呼吸', '专注', '接纳'],
        'calm': ['平衡', '冥想', '宁静', '和谐'],
        'confused': ['思考', '探索', '方向', '澄清']
      };
      
      // 获取主要情绪对应的关键词
      this.keywords = commonKeywords[this.mainEmotion] || ['成长', '学习', '健康'];
      
      // 根据健康分数生成建议
      if (this.healthScore >= 80) {
        this.suggestions = [
          '继续保持良好的心态，分享你的积极能量',
          '设定新的成长目标，挑战自我',
          '帮助他人，传递快乐'
        ];
      } else if (this.healthScore >= 60) {
        this.suggestions = [
          '保持规律作息，充足的睡眠很重要',
          '多参与户外活动，接触大自然',
          '培养兴趣爱好，丰富生活'
        ];
      } else {
        this.suggestions = [
          '尝试深呼吸和冥想，缓解压力',
          '寻求亲友支持，分享你的感受',
          '必要时寻求专业心理咨询'
        ];
      }
      
      // 模拟生成会员专属的情绪根源分析
      this.emotionRootAnalysis = '根据您的日记内容分析，您最近的情绪变化可能主要源于工作压力和生活节奏调整。建议您关注工作与生活的平衡，特别是在项目紧张期要注意自我调节。'
      
      // 模拟生成会员专属的个性化调节方案
      this.personalizedSolutions = [
        {
          type: '冥想',
          title: '5分钟呼吸冥想',
          description: '专注于呼吸，帮助快速平静情绪'
        },
        {
          type: '运动',
          title: '办公室伸展运动',
          description: '缓解久坐带来的身体紧张'
        },
        {
          type: '文字疏导',
          title: '情绪日记深入练习',
          description: '通过写作探索情绪背后的想法'
        }
      ]
      
      // 推荐文章（保持固定的文章列表）
      this.recommendedArticles = [
        { title: '情绪管理的科学方法', readTime: '4分钟', tag: '管理', tagColor: 'purple' },
        { title: '提升幸福感的日常习惯', readTime: '5分钟', tag: '积极', tagColor: 'green' },
        { title: '工作与生活的平衡艺术', readTime: '6分钟', tag: '平衡', tagColor: 'blue' }
      ];
    },
    
    // 格式化日期
    formatDate(date) {
      if (this.selectedPeriod === 'month') {
        return date.getDate() + '日'
      } else if (this.selectedPeriod === 'quarter' || this.selectedPeriod === 'year') {
        return (date.getMonth() + 1) + '月'
      }
      return ''
    },
    
    // 获取情绪对应的颜色
    getEmotionColor(emotion) {
      const emotionColors = {
        '开心': '#ff9e9e',
        '平静': '#a8d8ea',
        '焦虑': '#ffb3b3',
        '伤心': '#98d8c8',
        '成长': '#f7d94c'
      }
      return emotionColors[emotion] || '#a8d8ea'
    },
    
    // 获取折线图路径（使用平滑曲线）
    getLinePath() {
      if (this.chartData.length === 0) return ''
      
      let path = ''
      this.chartData.forEach((value, index) => {
        const x = (index / (this.chartData.length - 1)) * 100
        const y = 100 - value * 10
        
        if (index === 0) {
          path += `M ${x} ${y}`
        } else {
          // 使用平滑曲线代替直线段，使线条更流畅
          const prevIndex = index - 1
          const prevX = (prevIndex / (this.chartData.length - 1)) * 100
          const prevY = 100 - this.chartData[prevIndex] * 10
          
          // 计算控制点，用于绘制平滑曲线
          const cp1x = prevX + (x - prevX) / 3
          const cp1y = prevY
          const cp2x = x - (x - prevX) / 3
          const cp2y = y
          
          path += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${x} ${y}`
        }
      })
      
      return path
    },
    
    // 获取区域填充路径
    getAreaPath() {
      if (this.chartData.length === 0) return ''
      
      let path = ''
      const lastIndex = this.chartData.length - 1
      
      // 开始点
      path += `M 0 100`
      
      // 绘制到底部
      this.chartData.forEach((value, index) => {
        const x = (index / lastIndex) * 100
        const y = 100 - value * 10
        
        if (index === 0) {
          path += ` L ${x} ${y}`
        } else {
          // 使用与线条相同的平滑曲线
          const prevIndex = index - 1
          const prevX = (prevIndex / lastIndex) * 100
          const prevY = 100 - this.chartData[prevIndex] * 10
          
          const cp1x = prevX + (x - prevX) / 3
          const cp1y = prevY
          const cp2x = x - (x - prevX) / 3
          const cp2y = y
          
          path += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${x} ${y}`
        }
      })
      
      // 结束点
      path += ` L 100 100 Z`
      
      return path
    },
    
    // 高亮数据点
    highlightPoint(index) {
      this.highlightedPoint = index
    },
    
    // 处理图表鼠标移动
    handleChartMouseMove(event) {
      const chartContainer = this.$refs.chartContainer
      if (!chartContainer) return
      
      const rect = chartContainer.getBoundingClientRect()
      const x = event.clientX - rect.left
      const y = event.clientY - rect.top
      
      // 计算最近的数据点
      const pointWidth = rect.width / (this.chartData.length - 1)
      const closestIndex = Math.round(x / pointWidth)
      
      if (closestIndex >= 0 && closestIndex < this.chartData.length) {
        this.tooltipLeft = closestIndex * pointWidth + 10
        this.tooltipTop = rect.height - this.chartData[closestIndex] * 10 - 30
        this.tooltipContent = `日期：${this.formatDate(this.chartDates[closestIndex])}\n评分：${this.chartData[closestIndex]}分`
        this.tooltipVisible = true
      }
    },
    
    // 处理图表鼠标离开
    handleChartMouseLeave() {
      this.tooltipVisible = false
      this.highlightedPoint = -1
    },
    
    // 导出报告
    exportReport() {
      this.exportMessage = '报告导出中...'
      this.exportSuccess = false
      this.showExportMessage = true
      
      // 模拟导出过程
      setTimeout(() => {
        this.exportMessage = '导出成功'
        this.exportSuccess = true
        
        // 2秒后隐藏消息
        setTimeout(() => {
          this.showExportMessage = false
        }, 2000)
      }, 2000)
    },
    
    // 打开文章
    openArticle(index) {
      // 这里可以实现文章详情页的跳转
      console.log('打开文章:', this.recommendedArticles[index].title)
      // 模拟跳转
      alert(`即将打开文章：${this.recommendedArticles[index].title}`)
    }
  }
}
</script>

<style scoped>
/* 全局CSS变量定义 - 莫兰迪色系 */
:root {
  --morandi-blue: #8dabc4;
  --morandi-pink: #e5b9b6;
  --morandi-green: #a8c686;
  --morandi-yellow: #e6ccaf;
  --morandi-purple: #b8a9c9;
  --light-bg: #f9f9f9;
  --text-primary: #666666;
  --text-secondary: #999999;
  --white: #ffffff;
  --light-gray: #f0f0f0;
  --border-radius: 12px;
  --transition: all 0.3s ease;
}

/* 页面整体样式 */
.emotion-analysis-page {
  min-height: 100vh;
  background-color: var(--light-bg);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  color: var(--text-primary);
  line-height: 1.6;
}

/* 顶部导航栏 */
.emotion-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 30px;
  background-color: var(--white);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-button {
  background: none;
  border: none;
  font-size: 16px;
  color: var(--text-primary);
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 8px;
  transition: var(--transition);
}

.back-button:hover {
  background-color: var(--light-gray);
  transform: scale(1.03);
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.export-button {
  width: 100px;
  height: 36px;
  background-color: var(--morandi-blue);
  color: var(--white);
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: var(--transition);
}

.export-button:hover {
  transform: scale(1.03);
  opacity: 0.9;
}

/* 筛选区 */
.filter-section {
  padding: 20px 0;
  text-align: center;
}

.filter-buttons {
  display: inline-flex;
  gap: 15px;
}

.filter-btn {
  padding: 8px 20px;
  background-color: var(--section-bg);
    color: var(--text-light);
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: var(--transition);
}

.filter-btn.active {
    background-color: var(--primary-color);
    color: white;
}

.filter-btn:hover:not(.active) {
  transform: scale(1.03);
  background-color: var(--light-border);
}

/* 核心数据区 */
.core-data-section {
  max-width: 1200px;
  width: 75%;
  margin: 0 auto 40px;
}

/* 情绪趋势图容器 */
.trend-chart-container {
  background-color: var(--white);
  border-radius: var(--border-radius);
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.chart-wrapper {
  height: 300px;
  position: relative;
}

.chart-content {
  height: 100%;
  position: relative;
  cursor: pointer;
}

/* 图表网格 */
.chart-grid {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.grid-line {
  position: absolute;
  left: 0;
  right: 0;
  height: 1px;
  background-color: #f0f0f0;
}

/* 坐标轴 */
.y-axis {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 30px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0 5px;
}

.y-label {
  font-size: 12px;
  color: var(--text-secondary);
  text-align: right;
  margin-bottom: -8px;
}

.x-axis {
  position: absolute;
  bottom: 0;
  left: 30px;
  right: 0;
  height: 30px;
  display: flex;
  justify-content: space-between;
  padding: 5px 0;
}

.x-label {
  font-size: 12px;
  color: var(--text-secondary);
  text-align: center;
  position: relative;
  transform: translateX(-50%);
}

/* 折线图 */
.line-chart {
  position: absolute;
  top: 0;
  left: 30px;
  right: 0;
  bottom: 30px;
}

.chart-svg {
  width: 100%;
  height: 100%;
}

.chart-svg circle {
  transition: all 0.3s ease;
  transform-origin: center;
}

.chart-svg circle.active {
  r: 2;
  stroke-width: 0.8;
  transform: scale(1.4);
}

/* 简化动画效果 */
.chart-svg path {
  animation: none; /* 移除动画以确保完整显示 */
}

/* 数据点气泡 */
.data-tooltip {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.7);
  color: var(--white);
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 12px;
  white-space: pre-line;
  z-index: 10;
  pointer-events: none;
}

/* 情绪总结卡片 */
.summary-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.summary-card {
    flex: 1;
    background-color: var(--card-bg);
    border-radius: var(--radius-md);
  padding: 20px;
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: var(--transition);
}

.summary-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 14px;
  font-weight: 500;
  margin: 0;
}

.emotion-tag {
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0;
}

.emotion-percentage {
  font-size: 12px;
  color: var(--text-secondary);
  margin: 0;
}

/* 关键词 */
.keywords {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin: 10px 0;
}

.keyword-tag {
  background-color: var(--light-gray);
  color: var(--text-primary);
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
}

/* 健康度进度条 */
.health-progress-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px 0;
}

.health-progress-bar {
  flex: 1;
  height: 8px;
  background-color: var(--light-gray);
  border-radius: 4px;
  overflow: hidden;
}

.health-progress-fill {
  height: 100%;
  background-color: var(--morandi-yellow);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.health-score {
  font-weight: bold;
  font-size: 16px;
}

/* 疏导建议区 */
.suggestions-section {
  background-color: var(--white);
  border-radius: var(--border-radius);
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.suggestions-card {
  width: 100%;
}

.suggestions-title {
  font-size: 18px;
  color: var(--morandi-blue);
  margin: 0 0 15px 0;
}

/* 会员专属区域样式 */
.member-exclusive-section {
  margin-top: 30px;
}

.root-analysis-card,
.solutions-card {
  background-color: var(--white);
  border-radius: var(--border-radius);
  padding: 24px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  border: 1px solid var(--morandi-purple);
}

.analysis-content {
  color: var(--text-secondary);
  line-height: 1.6;
  margin-top: 12px;
}

.solutions-list {
  margin-top: 16px;
}

.solution-item {
  background-color: #f9f7fd;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
}

.solution-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.solution-type {
  background-color: var(--morandi-purple);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-right: 12px;
}

.solution-title {
  font-weight: 600;
  color: var(--text-primary);
}

.solution-description {
  color: var(--text-secondary);
  font-size: 14px;
}

/* 非会员引导区域 */
.non-member-section {
  margin-top: 30px;
}

.upgrade-hint-card {
  background: linear-gradient(135deg, #f9f7fd 0%, #fdfbf9 100%);
  border: 1px dashed var(--morandi-purple);
  border-radius: var(--border-radius);
  padding: 20px;
  cursor: pointer;
  transition: var(--transition);
}

.upgrade-hint-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(179, 157, 219, 0.1);
}

.upgrade-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.upgrade-icon {
  font-size: 24px;
}

.upgrade-text h4 {
  color: var(--text-primary);
  font-size: 16px;
  margin-bottom: 4px;
}

.upgrade-text p {
  color: var(--text-secondary);
  font-size: 14px;
}

.upgrade-btn {
  margin-left: auto;
  padding: 8px 20px;
  background-color: var(--morandi-purple-dark);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 14px;
  cursor: pointer;
  transition: var(--transition);
}

.upgrade-btn:hover {
  background-color: #9575CD;
  transform: scale(1.05);
}

/* 会员引导浮层样式 */
.member-guide-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background-color: var(--white);
  border-radius: var(--border-radius);
  width: 100%;
  max-width: 400px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  padding: 20px 24px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.modal-header h3 {
  color: var(--text-primary);
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: var(--transition);
}

.close-btn:hover {
  background-color: var(--light-gray);
}

.modal-body {
  padding: 20px 24px;
}

.benefits-preview {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 20px;
}

.benefit-item {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #f9f7fd;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid var(--morandi-purple);
}

.benefit-icon {
  font-size: 18px;
}

.benefit-text {
  color: var(--text-primary);
  font-size: 14px;
}

.modal-description {
  color: var(--text-secondary);
  text-align: center;
  line-height: 1.5;
}

.modal-footer {
  padding: 0 24px 24px;
  display: flex;
  gap: 12px;
}

.cancel-btn,
.go-member-btn {
  flex: 1;
  padding: 12px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: var(--transition);
}

.cancel-btn {
  background-color: var(--white);
  color: var(--text-primary);
  border: 1px solid var(--light-gray);
}

.cancel-btn:hover {
  background-color: var(--light-gray);
}

.go-member-btn {
  background-color: var(--morandi-purple-dark);
  color: white;
  border: none;
}

.go-member-btn:hover {
  background-color: #9575CD;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(179, 157, 219, 0.3);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .benefits-preview {
    grid-template-columns: 1fr;
  }
  
  .upgrade-content {
    flex-direction: column;
    text-align: center;
  }
  
  .upgrade-btn {
    margin-left: 0;
    margin-top: 12px;
  }
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.suggestion-dot {
  width: 8px;
  height: 8px;
  background-color: var(--morandi-blue);
  border-radius: 50%;
  margin-top: 6px;
  flex-shrink: 0;
}

.suggestion-text {
  font-size: 14px;
  color: var(--text-primary);
  line-height: 1.6;
}

/* 没有数据时的样式 */
.no-data-container {
  background-color: var(--white);
  border-radius: var(--border-radius);
  padding: 60px 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.no-data-content {
  text-align: center;
}

.no-data-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.7;
}

.no-data-title {
  font-size: 24px;
  color: var(--text-primary);
  margin: 0 0 10px 0;
}

.no-data-description {
  font-size: 16px;
  color: var(--text-secondary);
  margin: 0 0 30px 0;
}

.start-writing-btn {
  padding: 12px 32px;
  background-color: var(--morandi-blue);
  color: var(--white);
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: var(--transition);
}

.start-writing-btn:hover {
  transform: scale(1.05);
  opacity: 0.9;
}

/* 底部相关推荐 */
.recommendations-section {
  max-width: 1200px;
  width: 75%;
  margin: 0 auto 40px;
}

.recommendations-title {
  font-size: 16px;
  color: #888888;
  margin: 0 0 20px 0;
}

.recommendations-list {
  display: flex;
  gap: 20px;
  overflow-x: auto;
  padding-bottom: 10px;
}

.article-card {
  flex: 0 0 300px;
  background-color: var(--white);
  border-radius: var(--border-radius);
  padding: 20px;
  cursor: pointer;
  transition: var(--transition);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.article-card:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.article-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 10px 0;
  color: var(--text-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.article-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.article-time {
  font-size: 12px;
  color: var(--text-secondary);
}

.article-tag {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}

.tag-blue {
  background-color: rgba(141, 171, 196, 0.2);
  color: var(--morandi-blue);
}

.tag-green {
  background-color: rgba(168, 198, 134, 0.2);
  color: var(--morandi-green);
}

.tag-purple {
  background-color: rgba(184, 169, 201, 0.2);
  color: var(--morandi-purple);
}

.tag-yellow {
  background-color: rgba(230, 204, 175, 0.2);
  color: var(--morandi-yellow);
}

/* 导出提示 */
.export-message {
  position: fixed;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: var(--white);
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 14px;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.export-message.success {
  background-color: var(--morandi-green);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 1199px) {
  .core-data-section,
  .recommendations-section {
    width: 90%;
  }
}

@media (max-width: 768px) {
  .emotion-header {
    padding: 15px 20px;
  }
  
  .page-title {
    font-size: 18px;
  }
  
  .core-data-section,
  .recommendations-section {
    width: 95%;
  }
  
  .summary-cards {
    flex-direction: column;
  }
  
  .summary-card {
    height: auto;
    min-height: 120px;
  }
  
  .recommendations-list {
    gap: 15px;
  }
  
  .article-card {
    flex: 0 0 250px;
  }
  
  .filter-buttons {
    width: 100%;
    overflow-x: auto;
    padding: 0 10px;
  }
}

@media (max-width: 480px) {
  .back-button,
  .export-button {
    font-size: 14px;
  }
  
  .export-button {
    width: 80px;
    height: 32px;
  }
  
  .article-card {
    flex: 0 0 200px;
    padding: 15px;
  }
  
  .chart-wrapper {
    height: 250px;
  }
}
</style>